package com.qc.common;

import java.io.IOException;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.TokenUtil;

public class QiNiuUtil {
    
    //设置好账号的ACCESS_KEY和SECRET_KEY
    private static String ACCESS_KEY = TokenUtil.ACCESS_KEY;
    private static String SECRET_KEY = TokenUtil.SECRET_KEY;

    //要上传的空间 
    private static String bucketname = TokenUtil.IMAGE_BUCKET; //填写新建的那个存储空间对象的名称

    //密钥配置 
    private static Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
    
    

    //简单上传，使用默认策略，只需要设置上传的空间名就可以了  
    public static String getUpToken(){  
        return auth.uploadToken(bucketname);  
    }
    
    /**
     * 七牛普通上传   
     * FilePath 上传文件目录  
     * key 上传到七牛后保存的文件名  
     * @param FilePath
     * @param key
     * @throws IOException
     */
    public static void upload(String FilePath,String key) throws IOException{  
      try {
          
        //创建上传对象  
         UploadManager uploadManager = new UploadManager();
        //调用put方法上传  
        Response res = uploadManager.put(FilePath, key, getUpToken());  
        //打印返回的信息  
        System.out.println(res.isOK());
        System.out.println(res.bodyString());   
        } catch (QiniuException e) {  
            Response r = e.response;  
            // 请求失败时打印的异常的信息  
            System.out.println(r.toString());  
            try {  
                //响应的文本信息  
              System.out.println(r.bodyString());  
            } catch (QiniuException e1) {  
                //ignore  
            }  
        }         
    }
}
